package com.topisv.tms.task.prioritySend;

import java.lang.management.ManagementFactory;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.topisv.tms.entity.JobConfig;
import com.topisv.tms.entity.OrderBackTask;
import com.topisv.tms.entity.interfacetask.InterfaceTaskEnum;
import com.topisv.tms.repository.JobConfigDao;
import com.topisv.tms.service.prioritySend.OrderBackTaskProcessService;
import com.topisv.tms.service.prioritySend.OrderBackTaskService;

/**
 * 发货单任务提供类 Date Author Version Description
 * ---------------------------------------------------------- 2015-5-8 CC 1.0
 * Create
 */
@Component
@Lazy(false)
public class OrderBackTaskProvider implements InitializingBean {

	private Logger logger = LoggerFactory.getLogger(getClass());

	private BlockingQueue<OrderBackTask> taskQueue = new ArrayBlockingQueue<OrderBackTask>(1000);

	@Autowired
	private OrderBackTaskService taskService;
	@Autowired
	private OrderBackTaskProcessService taskProcessService;
	@Autowired
	private JobConfigDao jobConfigDao;

	private String node;
	private int MAX_ROWS = 100;
	private int THREAD_CNT = 1; // 注：如果大于1， 可能会出现多次消费的情况。取决于接口发送的速度。

	@Scheduled(cron = "0/30 * * * * *")
	public void execute() {

		try {
			
			//查询该JOB任务是否启动，start启动，否则关闭
			JobConfig jobConfig = jobConfigDao.findJobConfigByClassName("OrderBackTaskProvider");
			if (jobConfig != null) {
				if ("start".equals(jobConfig.getStatus())) {
					
					//锁定数据
					taskService.lockTask(getNode(), InterfaceTaskEnum.STATUS_READY, MAX_ROWS);

					// 这里查找所有未从发送过接口的数据和(失败并且次数<3)的单子，
					List<OrderBackTask> taskList = taskService.findTask(InterfaceTaskEnum.STATUS_READY, getNode(), 0, MAX_ROWS);
					for (OrderBackTask task : taskList) {
						if (!taskQueue.contains(task)) {
							taskQueue.offer(task);
						}
					}
				}else {
					taskQueue.clear();
				}
			}
			
		} catch (Exception ex) {
			logger.error("TTKDEXOrderBackTaskProvider case some error, please check soon.", ex);
		}
	}

	public String getNode() {
		if (node == null) {
			String name = ManagementFactory.getRuntimeMXBean().getName();
			node = name.substring(name.indexOf("@") + 1);
		}
		return node;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		while (THREAD_CNT-- > 0) {
			new OrderBackTaskWorker(taskQueue, taskService, taskProcessService).start();
		}
	}
}
